package ai.tuobot.sdk.util

import android.content.Context
import android.media.MediaMetadataRetriever
import android.os.Build
import androidx.annotation.RequiresApi
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder

internal object BufferUtil {
    @RequiresApi(Build.VERSION_CODES.S)
    fun getSamplingRate(context: Context, audioData: ByteArray, fileType: String): Int {
        return when (fileType.lowercase()) {
            "mp3" -> getSamplingRateFromMp3Stream(context, audioData)
            "wav" -> getSamplingRateFromWavStream(audioData)
            else -> throw IllegalArgumentException("Unsupported file type: $fileType")
        }
    }

    @RequiresApi(Build.VERSION_CODES.S)
    fun getSamplingRateFromMp3Stream(context: Context, mp3Data: ByteArray): Int {
        val retriever = MediaMetadataRetriever()
        var samplingRate = -1

        // Step 1: Write the input stream to a temporary file
        val tempFile = File(context.cacheDir, "temp_mp3.mp3")
        FileOutputStream(tempFile).use { outputStream ->
            outputStream.write(mp3Data)
        }

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                // Step 2: Set data source using the file path for Android 12 and above
                retriever.setDataSource(tempFile.absolutePath)
            } else {
                // Handle older Android versions with alternative logic
                // For older versions, setDataSource works with file descriptors
                val fileDescriptor = FileInputStream(tempFile).fd
                retriever.setDataSource(fileDescriptor)
            }

            // Step 3: Extract the sample rate
            val sampleRateString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_SAMPLERATE)
            samplingRate = sampleRateString?.toIntOrNull() ?: 24000

        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            retriever.release()
            tempFile.delete()  // Clean up the temp file
        }

        return samplingRate
    }

    fun getSamplingRateFromWavStream(audioData: ByteArray): Int {
        // WAV files store metadata in their header
        val header = audioData.take(44).toByteArray()
        return ByteBuffer.wrap(header, 24, 4).order(ByteOrder.LITTLE_ENDIAN).int // Extract sample rate from bytes 24-27
    }

    fun getPropertiesFromMp3Stream(context: Context, mp3Data: ByteArray): Pair<Int, Int> {
        val retriever = MediaMetadataRetriever()
        var samplingRate = -1
        var bitRate = -1

        // Step 1: Write the input stream to a temporary file
        val tempFile = File(context.cacheDir, "temp_mp3.mp3")
        FileOutputStream(tempFile).use { outputStream ->
            outputStream.write(mp3Data)
        }

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                // For Android 12+ use file path
                retriever.setDataSource(tempFile.absolutePath)
            } else {
                // For older Android versions, use FileDescriptor
                val fileDescriptor = FileInputStream(tempFile).fd
                retriever.setDataSource(fileDescriptor)
            }

            // Extract sample rate
            val sampleRateString =
                retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_SAMPLERATE)
            samplingRate = sampleRateString?.toIntOrNull() ?: -1

            // Extract bit rate
            val bitRateString = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE)
            bitRate = bitRateString?.toIntOrNull() ?: -1

        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            retriever.release()
            tempFile.delete() // Clean up the temp file
        }

        return Pair(samplingRate, bitRate)
    }

    private fun getPropertiesFromWavStream(wavData: ByteArray): Pair<Int, Int> {
        // Implement WAV parsing logic if needed
        // Return Pair(samplingRate, bitRate)
        throw UnsupportedOperationException("WAV properties extraction is not implemented")
    }

}